import requests
from requests.exceptions import RequestException
import re
import  json
def get_one_page(url):
	try:
		res = requests.get(url)
		if res.status_code == 200:
			return res.text
		return None
	except RequestException:
		return None
def parse_one_page (html):
	pattern = re.compile('<dd>.*?data-val="(.*?)">.*?data-src="(.*?)".*?title=(.*?)>', re.S)
	items = re.findall(pattern, html)
	# print(items)
	print('#'*1000)
	for item in items:
		yield {
			'index': item[0],
			'image': item[1],
			'title': item[2]
		}
	
	print('*'*100)

def write_to_file(content):
	with open('猫眼预售电影.txt', 'a', encoding='utf-8') as f:
		f.write(json.dumps(content,ensure_ascii=False, indent=2))
def main():
	url = 'https://maoyan.com/films?showType=2'
	html = get_one_page(url)
	# print(ret.content.decode())
	generators = parse_one_page(html)
	for item in generators:
		print(item)
		write_to_file(item)
if __name__ == '__main__':
	main()
